import Vue from 'vue'
import Vuex from 'vuex'
import {authLogin} from '../api/login'
import http from '@/utils/http'

Vue.use(Vuex);

const store = new Vuex.Store({
	state: {
		hasLogin: false,
		userInfo: {},
	},
	mutations: {
		login(state, provider) {
			state.hasLogin = true;
			state.userInfo = provider.member;
			uni.setStorage({//缓存用户登陆状态
			    key: 'user',
			    data: provider
			});
			uni.setStorage({//缓存用户登陆状态
			    key: 'loginTime',
			    data: new Date().getTime() / 1000
			});
			uni.setStorage({//缓存用户登陆状态
			    key: 'userInfo',
			    data: provider.member
			})
			uni.setStorage({//缓存用户登陆状态
			    key: 'accessToken',
			    data: provider.access_token
			})
			uni.setStorage({//缓存用户登陆状态
			    key: 'refreshToken',
			    data: provider.refresh_token
			})
			const user_info = uni.getStorageSync('user_info');
			if (!!user_info) {
				const oauthClientParams = {}
				/*  #ifdef MP-WEIXIN */
				oauthClientParams.oauth_client = 'wechatMp';
				/*  #endif  */
				/*  #ifndef MP-WEIXIN */
				oauthClientParams.oauth_client = 'wechat';
				/*  #endif  */
				const userInfo = JSON.parse(user_info);
				console.log(userInfo)
				http.post(authLogin, {
					...userInfo,
					...oauthClientParams,
					gender: userInfo.sex || userInfo.gender,
					oauth_client_user_id: userInfo.openid || userInfo.openId,
					head_portrait: userInfo.headimgurl || userInfo.avatarUrl,
				})
			}
		},
		logout(state) {
			state.hasLogin = false;
			state.userInfo = {};
			uni.removeStorage({
                key: 'userInfo'
            })
			uni.removeStorage({
                key: 'accessToken'
            })
		}
	},
	actions: {
	}
})

export default store
